package com.daoshu.mds.system.component;

import com.daoshu.component.response.ResponseCallBack;
import com.daoshu.component.response.ResponseCriteria;
import com.daoshu.component.snowflake.SnowFlake;
import com.daoshu.mds.system.component.annotations.AuthAnnotation;
import com.daoshu.mds.system.mapper.AccountRoleMapper;
import com.daoshu.mds.system.service.IAuthLogService;
import com.daoshu.mds.system.utils.RequestKit;
import com.daoshu.system.entity.AccountRoleEntity;
import com.daoshu.system.entity.CpAuthLog;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @author zhangmingxin
 */
@Slf4j
@Aspect
@Component
@AllArgsConstructor
public class AuthLogAop {
    private final IAuthLogService authLogService;
    private final SnowFlake snowFlake = new SnowFlake();
    private final RequestKit kit;
    private final AccountRoleMapper accountRoleMapper;
    private final static String DELETE_FLAG = "deletePersonRole";
    @Pointcut(value = "@annotation(com.daoshu.mds.system.component.annotations.AuthAnnotation)")
    public void pointCut(){
    }

    @Around("pointCut()")
    public Object around(ProceedingJoinPoint joinPoint){
        RequestAttributes ra = RequestContextHolder.getRequestAttributes();
        ServletRequestAttributes sra = (ServletRequestAttributes) ra;
        HttpServletRequest request = sra.getRequest();
        String ip = kit.getIp(request);
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        Method method = signature.getMethod();
        AuthAnnotation annotation = method.getAnnotation(AuthAnnotation.class);
        List<CpAuthLog> logList = new ArrayList<>();
        if(annotation!=null){
            String opval = annotation.opVal();
            CpAuthLog logs;
            LocalDateTime now = LocalDateTime.now();
            //删除角色
            if(DELETE_FLAG.equalsIgnoreCase(opval)){
                //查询要删除的角色
                String accountId = (String) joinPoint.getArgs()[0];
                if(!StringUtils.isEmpty(accountId)){
                    List<Map<String,String>> roleList = accountRoleMapper.getRoleListByAccountId(accountId);
                    for (Map<String, String> map : roleList) {
                        logs = new CpAuthLog();
                        logs.setId(snowFlake.nextId());
                        logs.setOrgId(map.getOrDefault("orgid",""));
                        logs.setOrg(map.getOrDefault("orgname",""));
                        logs.setNumber(map.getOrDefault("number",""));
                        logs.setName(map.getOrDefault("name",""));
                        logs.setAuthType("0");
                        logs.setAuthRole(map.get("roleid"));
                        logs.setAuthPerson(map.get("accountid"));
                        logs.setCreateTime(now);
                        logs.setIp(ip);
                        logList.add(logs);
                    }
                }
            }else{//设置角色
                List<AccountRoleEntity> accountRoleEntitys = (List<AccountRoleEntity>) joinPoint.getArgs()[0];
                for (AccountRoleEntity accountRoleEntity : accountRoleEntitys) {
                    List<Map<String,String>> list = accountRoleMapper.getPersonInfoByAccountId(accountRoleEntity.getAccountId());
                    logs = new CpAuthLog();
                    logs.setId(snowFlake.nextId());
                    if(list!=null && !list.isEmpty()){
                        Map<String,String> map = list.get(0);
                        logs.setOrgId(map.getOrDefault("orgid",""));
                        logs.setOrg(map.getOrDefault("orgname",""));
                        logs.setNumber(map.getOrDefault("number",""));
                        logs.setName(map.getOrDefault("name",""));
                    }
                    logs.setAuthType("1");
                    logs.setAuthRole(accountRoleEntity.getRoleId());
                    logs.setAuthPerson(accountRoleEntity.getAccountId());
                    logs.setCreateTime(now);
                    logs.setIp(ip);
                    logList.add(logs);
                }
            }
        }
        try {
            joinPoint.proceed();
            if(logList.size() > 0){
                authLogService.saveBatch(logList);
            }
        } catch (Throwable throwable) {
            log.error("error==>{}", throwable.getMessage());
        }
        return new ResponseCallBack() {
            @Override
            public void execute(ResponseCriteria responseCriteria, Object... objects) {

            }
        }.sendRequest();
    }

}
